<template>
    <div class="body_textarea_layout">
        <div class="body_textarea_box" style="top: 0px;" :style="{'height':height - 40 + 'px' }">
            <textarea ref="header"></textarea>
        </div>
        <quickInsert :editor="editor" :mini="true"></quickInsert>
    </div>
</template>
<script>
    import { mapState } from 'vuex';

    import quickInsert from './quickInsert';

    let CodeMirror = require("codemirror/lib/codemirror");
    import "codemirror/lib/codemirror.css";
    import "codemirror/theme/mdn-like.css";
    import "codemirror/mode/javascript/javascript.js";
    import "codemirror/addon/fold/foldgutter.css";
    import "codemirror/addon/fold/foldcode.js";
    import "codemirror/addon/fold/foldgutter.js";
    import "codemirror/addon/fold/brace-fold.js";
    import "codemirror/addon/fold/comment-fold.js";
    import "codemirror/addon/edit/matchbrackets";
    import 'codemirror/addon/hint/javascript-hint'
    import 'codemirror/addon/hint/show-hint'
    import 'codemirror/keymap/sublime.js'
    import 'codemirror/keymap/emacs.js'
    import 'codemirror/keymap/vim.js'

    export default {
        components: {
            quickInsert,
        },
        props: ['height', 'before', 'ChangeValue'],
        data() {
            return {
                editor: null,
            }
        },
        mounted() {
            this.editor = CodeMirror.fromTextArea(this.$refs.header, {
                mode: 'text/javascript',
                indentWithTabs: true,
                smartIndent: false,
                lineNumbers: true,
                lineWrapping: true,
                foldGutter: true,
                matchBrackets: true,
                gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
                theme: 'mdn-like',
            });
            this.editor.on('beforeChange', (instance, changeObj) => {
                if (changeObj.origin == '+input' && (changeObj.text == '\'' || changeObj.text == '\"')) {
                    var _str = this.editor.getSelection();
                    if (_str.toString().length > 0) {
                        this.editor.replaceSelection(_str + _str + changeObj.text);
                    };
                    // console.log(true);
                };
            });
            this.renderData();
        },
        methods: {
            ChangeEvent() {
                this.ChangeValue('before', this.editor.getValue());
            },
            closeChange() {
                this.editor.off('change', this.ChangeEvent);
            },
            restore() {
                this.renderData();
            },
            renderData() {
                this.editor.setValue(this.before);
                this.$nextTick(() => {
                    this.editor.on('change', this.ChangeEvent);
                });
            },
            refreshEditor() {
                this.editor.refresh();
            },
        },
    }


</script>